<template>
	<view class="wrap">
		<div class="turtle_mes">
			<div class="inp_box">
				<uni-easyinput class="form_inp" v-model="formData.turtle_name" focus placeholder="输入爱龟的名字"/>
			</div>

			<div class="inp_box">
				<uni-easyinput class="form_inp" v-model="formData.turtle_varieties" placeholder="输入爱龟的品种"/>
			</div>

			<div class="inp_box">
				<view class="uni-list">
					<view class="uni-list-cell">
						<view class="uni-list-cell-left">
							出壳日期
						</view>
						<view class="uni-list-cell-db">
							<picker mode="date" :value="date" :start="startDate" :end="endDate" @change="bindDateChange" fields="month">
								<view class="uni-input date_text">{{date}}</view>
							</picker>
						</view>
					</view>
				</view>
				<!-- <uni-easyinput class="form_inp" v-model="formData.turtle_age" placeholder="输入爱龟的年龄（例：2年输入“两年”,5个月输入“5个月”）"/> -->
			</div>

			<div class="inp_box load_box" @click="upload">
            	<image class="add_record_img" :src="imageUrl?imageUrl:'../../static/record/add.png'" mode="aspectFill"/>
				<div class="upload_text">上传龟的照片,作为头像</div>
			</div>
		</div>
		<div class="add_turtle" @click="addTurtle">提交</div>
	</view>
</template>

<script>
	export default {
		components: {
			
		},
		data() {
			const currentDate = this.getDate({
				format: true
			})
			return {
                formData: {
                    turtle_name: "",
					turtle_varieties: "",
                },
				imageUrl: "",
				date: currentDate,
				nowTime: currentDate,
				turtleYear: "",
			}
		},
		computed: {
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			}
		},
		methods: {
			bindDateChange(e) {
				this.date = e.detail.value;
				this.turtleYear = this.getTurtleYear(this.date)
			},
			judgeDate(tomodifyDate){
			    return new Date().getTime()-new Date(tomodifyDate).getTime();
			},
			getTurtleYear(date){
				if(this.judgeDate((date+'-01'))<0){
					uni.showToast({
					   duration:3000,
					   icon: "none",
					   title: "选择日期不能大于当前日期",
					});
					this.date = this.getDate({
						format: true
					})
					return ;
				}
				var nowTime = (this.nowTime+'-01').split('-');
				console.log(nowTime,'nowTime');
				// 得到月数
				nowTime = [parseInt(nowTime[0]),parseInt(nowTime[1])];
				// 拆分年月日
				var theTime = (date+'-01').split('-');
				// 得到月数
				theTime = [parseInt(theTime[0]),parseInt(theTime[1])];
				var y = Math.abs(nowTime[0] - theTime[0]);
				var m = nowTime[1] - theTime[1];
				m = m!=0?`${m}个月`:'';
				y = y!=0?`${y}年`:'';
				return y+m;
			},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				// let day = date.getDate();

				if (type === 'start') {
					year = year - 60;
				} else if (type === 'end') {
					year = year + 2;
				}
				month = month > 9 ? month : '0' + month;
				// day = day > 9 ? day : '0' + day;
				return `${year}-${month}`;
			},
			addTurtle() {
				if ( this.formData.turtle_name && this.formData.turtle_varieties ) {
					uniCloud.callFunction({
						name: 'recordOfTurtle',
						data: {
							turtle_name: this.formData.turtle_name,
							turtle_varieties: this.formData.turtle_varieties,
							turtle_age: this.turtleYear,
							image_url: this.imageUrl,
							user_id: uni.getStorageSync('userId')
						},
						success(res) {
							uni.showToast({
								duration: 2000,
								icon: "success",
								title: "提交成功",
							});
							setTimeout(() => {
								uni.navigateBack()
							}, 2000);
						},
						fail(e) {
							console.log(e);
						}
					})
				} else {
					uni.showToast({
					   duration:3000,
				       icon: "none",
				       title: "请补充完整信息后提交",
				    });
				}
				
			},
			upload() {
				const that = this;
				// 选择图片，默认不设置count属性的话最多9张
				uni.chooseImage({
					success(res) {
						// 通过遍历调用uniCloud.uploadFile来批量上传
						uni.showLoading({
							title: "上传中..."
						})
						let filePath = res.tempFilePaths[0] // 选择图片的临时路径
						const name = res.tempFiles[0].name // 选择图片的名称.后缀名
						uniCloud.uploadFile({
							filePath, // 必传，要上传的文件对象临时路径
							cloudPath: Date.now() + "-" + name, // 必传，保存在云端的文件名，这样写上传后就是原本的名称与后缀名
							success(res) {
								let imageUrl = res.fileID //云端返回的图片地址
								that.imageUrl = imageUrl;
								console.log('imageUrl',imageUrl)
								// 调用云函数保存图片数据
								uniCloud.callFunction({
									name: "addImage", 
									// 传给云函数的数据，可根据自身需求进行改动
									data:{
										imageUrl: imageUrl, // 图片路径
										createTime: Date.now(), // 创建时间
									},
									success: res => {
										console.log(res)
									},
									fail: err => {
										console.log(err)
									},
									complete: () => {}
								})
							},
							fail(err) {
								console.log(err)
							},
							complete() {
								uni.hideLoading()
							}
						})
					}
				})
			},
		},
		onLoad() {
			
		}
	}
</script>

<style lang="scss" scoped>
.wrap{
	width: 100%;
	min-height: 100vh;
	overflow-x: hidden;
    padding: 20rpx;
	.turtle_mes {
		width: 100%;
		padding: 20px;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		.inp_box {
			width: 100%;
			padding-bottom: 20rpx;

			.add_record_img {
				width: 160rpx;
				height: 160rpx;
				border: 12rpx dashed #3d836d;
				padding: 12rpx;
			}
			
			.uni-list {
				width: 100%;
				height: 80rpx;
				line-height: 80rpx;
				border-radius: 8rpx;
				border: 1px solid #e5e5e5;
				color: #999;
				padding-left: 20rpx;
				.date_text {
					color: #333;
				}
				.uni-list-cell {
					display: flex;
				}
				.uni-list-cell-left {
					padding-right: 20rpx;
					font-size: 24rpx;
				}
			} 
		}
		.load_box {
			display: flex;
			flex-direction: column;
			align-items: center;
			.add_record_img {
				margin: 36rpx 0;
			}
		}
	}
	.add_turtle {
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		text-align: center;
		background: #3d836d;
		color: #fff;
		border-radius: 20rpx;
		font-size: 32rpx;
	}

}
</style>
